<?php

namespace App\Http\Controllers;

use App\Http\Requests\MeetingRoomRequest;
use Illuminate\Http\Request;
use App\Models\MeetingRoom;
use Illuminate\Support\Facades\Auth;

class MeetingRoomController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->only(['store', 'update', 'destroy']);
    }
    
    public function show()
    {
        $slogan = '会议预定系统';
        $lightboxSections = json_encode(MeetingRoom::LIGHTBOX_SECTIONS, JSON_UNESCAPED_UNICODE);
        $user = Auth::user();
        $room = intval(request('room', 1));

        return view('meetingroom', compact('user', 'room', 'lightboxSections', 'slogan'));
    }

    public function index(Request $request, MeetingRoom $meeting){
        $room = intval(request('room', 1));
        $data = $meeting->with('user')
            ->where("start_date", "<", $request->to)
            ->where("end_date", ">=", $request->from)
            ->where('room_id', $room)
            ->get();

        return response()->json(compact('data'));
    }

    public function store(MeetingRoomRequest $request, MeetingRoom $meeting){
        if (!Auth::check()) {
            return response()->json([
                'action' => 'error'
            ])->setStatusCode(403, 'Please login first!');
        }

        $meeting->room_id = $request->room_id;
        $meeting->department = strip_tags($request->department);
        $meeting->text = strip_tags($request->text);
        $meeting->start_date = $request->start_date;
        $meeting->end_date = $request->end_date;
        $meeting->create_user_id = Auth::user()->getAuthIdentifier();

        $meeting->save();

        return response()->json([
            "action"=> "inserted",
            "tid" => $meeting->id
        ]);
    }

    public function update($id, MeetingRoomRequest $request){
        $meeting = MeetingRoom::query()->findOrFail($id);

        $meeting->room_id = $request->room_id;
        $meeting->department = strip_tags($request->department);
        $meeting->text = strip_tags($request->text);
        $meeting->start_date = $request->start_date;
        $meeting->end_date = $request->end_date;
        $meeting->save();

        return response()->json([
            "action"=> "updated"
        ]);
    }

    public function destroy($id){
        $event = MeetingRoom::query()->findOrFail($id);
        $event->delete();

        return response()->json([
            "action"=> "deleted"
        ]);
    }

}
